import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:alipay_kit/alipay_kit_platform_interface.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/pay/recharge_entity.dart';
import 'package:ball_lion/server/api/pay_api.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/mine/my_contact_page.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/utils/web_pay.dart';
import 'package:ball_lion/module/pay/pay_bottom_sheet.dart';

class MyRechargeLogic extends GetxController {
  MyRechargeLogic({this.isSheet = false});
  final bool isSheet;
  List<RechargeEntity> list = [];
  bool agree = false;
  int? _currentIndex;
  PayEntity? currentOrder;
  int? androidPayType;
  StreamSubscription? alipayListener;
  late WeChatResponseSubscriber wechatListener;
  late final StreamSubscription? webPayListener;

  int? get currentIndex => _currentIndex;

  set currentIndex(int? value) {
    _currentIndex = value;
    update();
  }

  @override
  void onInit() {
    super.onInit();
    alipayListener = AlipayKitPlatform.instance.payResp().listen((event) async {
      log(event.result ?? "");
      if (event.resultStatus == 9000) {
        if (!isSheet) {
          Get.dialog(const QsDialog.alert(
            '您本次支付成功',
            confirmText: '我知道了',
          ));
          await User.fetchUserInfo(fetchFocus: false);
        } else {
          Toast.text("充值成功");
          navigator?.pop(true);
        }
      } else if (event.resultStatus == 6001) {
      } else {
        final flag = await Get.dialog(const QsDialog.alert(
            '您本次支付失败！\n如您确认已支付可联系客服',
            confirmText: '联系客服'));
        if (flag == true) {
          Get.to(const MyContactPage());
        }
      }
    });
    wechatListener = (response) async {
      if (response is WeChatPaymentResponse) {
        if (response.isSuccessful) {
          if (!isSheet) {
            Get.dialog(const QsDialog.alert(
              '您本次支付成功',
              confirmText: '我知道了',
            ));
            await User.fetchUserInfo(fetchFocus: false);
          } else {
            Toast.text("充值成功");
            navigator?.pop(true);
          }
        } else if (response.errCode == -2) {
        } else {
          final flag = await Get.dialog(const QsDialog.alert(
              '您本次支付失败！\n如您确认已支付可联系客服',
              confirmText: '联系客服'));
          if (flag == true) {
            Get.to(const MyContactPage());
          }
        }
        log('$response');
      }
    };
    Fluwx().addSubscriber(wechatListener);
    webPayListener = WebPay().payResp().listen((event) async {
      await User.fetchUserInfo(fetchFocus: false);
      if (isSheet) navigator?.pop(true);
    });
  }

  @override
  void onReady() async {
    super.onReady();
    User.fetchUserInfo(fetchFocus: false).then((value) => update());
    List<RechargeEntity>? result =
        await PayApi.getRechargeList(Platform.isIOS ? '2' : '1');
    if (result != null) {
      list = result;
      update();
    }
  }

  @override
  void onClose() {
    alipayListener?.cancel();
    Fluwx().removeSubscriber(wechatListener);
    WebPay().close(webPayListener);
    super.onClose();
  }

  void generateOrder(
      {double? payAmt, int? index, required PayMode payMode}) async {
    currentOrder = null;
    RechargeEntity? data;
    if (index != null) {
      data = list[index];
    }
    PayEntity? order = await PayApi.generatePay(
        itemId: data?.id, payAmt: payAmt, payMode: payMode, showLoading: true);
    if (order != null) {
      currentOrder = order;
      PayApi.androidPay(payMode, order.payCertificate!);
    }
  }

  void onAgree() {
    Utils.onEvent('wode_dxdl_xy', params: {'wode_dxdl_xy': agree ? '0' : '1'});
    agree = !agree;
    update();
  }

  Future pay() async {
    Utils.onEvent('charge_coin_select');
    RechargeEntity data = list[currentIndex!];
    final mode = await Get.bottomSheet(
        PayBottomSheet.recharge(
            price: data.payAmt.toString(),
            gold: data.gold ?? 0,
            description: data.description),
        isScrollControlled: true);
    if (mode != null) {
      PayMode payMode = mode;
      generateOrder(
          payAmt: data.payAmt?.toStringAsFixed(2).toDouble(),
          index: currentIndex,
          payMode: payMode);
    }
  }
}
